import 'dart:ui';
import 'package:flutter/painting.dart';
import 'package:hixing_app/views/test_view/test_matrix4/transform_vertex_model.dart';
import 'package:vector_math/vector_math_64.dart' as vector;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math' as math;
import 'package:get/get.dart';
import 'package:hixing_app/views/test_view/canvas_utils.dart';
import 'package:hixing_app/views/test_view/test_matrix4/rect_element_model.dart';

class TestMatrix4Demo extends StatefulWidget {
  @override
  _TestMatrix4DemoState createState() => _TestMatrix4DemoState();
}

class _TestMatrix4DemoState extends State<TestMatrix4Demo> {
  List<RectInfoModel> rectList = [];
  CanvasEventType? eventType;

  // 平移
  double dx = 100;
  double dy = 100;

  // 触摸点dx跟dy坐标跟起始dx dy修正
  double odx = 0;
  double ody = 0;

  bool isLock = true;

  // 缩放
  double scaleX = 1;
  double scaleY = 1;

  // 缩放的rect，
  Rect? scaleRenderRect;

  //svg  偏移量 ,用来计算触摸缩放的时候 点一下会放大的bug
  double correctSvgDx = 0;
  double correctSvgDy = 0;

  Size imgSize = Size(100, 100);

  // 旋转
  double rotationAngle = 0.0;
  Offset initialPosition = Offset(0, 0);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setPreferredOrientations(// 使设备横屏显示
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text('模板'),
      // ),
      body: Stack(
        children: [
          Listener(
            onPointerDown: (details) {
              // 获取点击的位置
              final RenderBox renderBox =
                  context.findRenderObject() as RenderBox;
              // 需要初始值加上默认的偏移量
              final globalPosition =
                  renderBox.localToGlobal(details.localPosition);
              initialPosition = details.localPosition; //details.localPosition;
              // 当前偏移量，使用0，0，绘制的矩形，需要减去dx跟dy的平移偏移量
              // final offsetLocal = globalPosition - Offset(dx, dy);

              //path 以原点为起始画的，使用canvas
              // final offsetToRotate = globalPosition -
              //     Offset(dx + imgSize.width / 2, dy + imgSize.height / 2);

              for (var element in rectList) {
                // 矩形域点击失效的情况，有可能是 LTRB的位置写错了
                // 判断逻辑： 如果点击的坐标在矩形域中，或者点击的坐标在path的范围内，就设置event 并且break循环;
                // 这里判断塞进去的矩形点击域

                // print(
                //     "当前事件点击：,$eventType，${element.rect.contains(globalPosition)},${element.rect}$globalPosition");
                if (element.rect.contains(globalPosition)) {
                  eventType = element.type;

                  break;
                } // 如果path不是null，证明是旋转后塞入的path，
                else if (element.path != null) {
                  // path画顶点坐标的时候，是以原点画的，这里需要加上原始的dx跟dy偏移量，因为在画path的时候，只能用原点开始，
                  if (element.path!.contains(globalPosition)) {
                    eventType = element.type;
                    // 处理平移事件
                    if (element.type == CanvasEventType.image) {
                      print("平移事件");
                      //平移偏移量修正,修正后
                      odx = globalPosition.dx - dx;
                      ody = globalPosition.dy - dy;
                    } else if (element.type == CanvasEventType.scale) {
                      // print("缩放事件");
                      // 缩放操作开始

                      // print("点击缩放icon");
                      //svgIcon 点击偏移量修正
                      // 计算缩放后的偏移量，如果还没开始缩放，就是原始尺寸的宽高
                      double computedWidth = scaleRenderRect == null
                          ? imgSize.width
                          : imgSize.width *
                              (scaleRenderRect!.width / imgSize.width);
                      double computedHeight = scaleRenderRect == null
                          ? imgSize.height
                          : imgSize.height *
                              (scaleRenderRect!.height / imgSize.height);

                      // 计算svgicon的偏移量，修正缩放的点击坐标
                      correctSvgDx = globalPosition.dx - (dx + computedWidth);
                      correctSvgDy = globalPosition.dy - (dy + computedHeight);
                    }
                    // else if(element.type == CanvasEventType.rotate){
                    //
                    // }
                    break;
                  }
                }
              }
            },
            onPointerUp: (_) {
              eventType = null;
            },
            onPointerMove: (details) {
              // 获取点击的位置
              final RenderBox renderBox =
                  context.findRenderObject() as RenderBox;
              // 需要初始值加上默认的偏移量
              final globalPosition =
                  renderBox.localToGlobal(details.localPosition);
              final newPosition = details.localPosition;
              final delta = newPosition - initialPosition;

              if (eventType == CanvasEventType.image) {
                // 平移元素操作
                setState(() {
                  dx = globalPosition.dx - odx;
                  dy = globalPosition.dy - ody;
                });
              } else if (eventType == CanvasEventType.scale) {
                double _currentDx = globalPosition.dx - dx - correctSvgDx;
                double _currentDy = globalPosition.dy - dy - correctSvgDy;

                Rect _rect;
                // if (isLock) {
                //   // 如果是锁定的，计算好尺寸比例，然后再塞进去盒子里
                //   double scaleW = _currentDx / imgSize.width;
                //   double scaleH = _currentDy / imgSize.height;
                //   // 如果锁定，使用均分的比例缩放，如果不锁定，就是不锁定的比例，获取缩放后的宽度，就是用计算好的缩放比例，用初始的宽高比计算最终渲染后的宽高
                //   double _lockScale = (scaleW + scaleH) / 2;
                //   // 把等比缩放的尺寸计算出来，画入rect里面
                //   _rect = ui.Rect.fromLTRB(
                //     0,
                //     0,
                //     imgSize.width * _lockScale,
                //     imgSize.height * _lockScale,
                //   );
                // } else {
                //
                // }
                // 如果不锁定，就根据手指触摸的坐标缩放就行了
                _rect = Rect.fromLTRB(0, 0, _currentDx < 20 ? 20 : _currentDx,
                    _currentDy < 20 ? 20 : _currentDy);
                scaleRenderRect = _rect;
                double scaleW = scaleRenderRect!.width / imgSize.width;
                double scaleH = scaleRenderRect!.height / imgSize.height;
                // 如果锁定，使用均分的比例缩放，如果不锁定，就是不锁定的比例
                double _lockScale = (scaleW + scaleH) / 2;
                if (isLock) {
                  // 如果锁定，等比缩放
                  scaleX = _lockScale;
                  scaleY = _lockScale;
                } else {
                  //如果没锁定，根据触摸的坐标缩放
                  scaleX = scaleW;
                  scaleY = scaleH;
                }
                setState(() {});
              } else if (eventType == CanvasEventType.rotate) {
                // 求出当前坐标的方位角
                final angle = math.atan2(delta.dy, delta.dx);

                // final rotationFactor = 0.01;
                // final angle = math.atan2(delta.dy, delta.dx) * rotationFactor;

                if (initialPosition != null) {
                  setState(() {
                    rotationAngle = angle;
                  });
                }
              }
            },
            child: CustomPaint(
              size: Size.infinite,
              painter: MyCustomPainter(
                  rotationAngle: rotationAngle,
                  scaleX: scaleX,
                  scaleY: scaleY,
                  imgSize: imgSize,
                  rectList: rectList,
                  dx: dx,
                  dy: dy),
            ),
          ),
          Positioned(
              top: 30,
              left: 30,
              child: Container(
                decoration: BoxDecoration(
                    color: Colors.black26,
                    borderRadius: BorderRadius.circular(40)),
                child: IconButton(
                  onPressed: () {
                    Get.back();
                  },
                  icon: Icon(
                    Icons.arrow_back,
                    color: Colors.yellowAccent,
                    size: 30,
                  ),
                ),
              ))
        ],
      ),
    );
  }
}

class MyCustomPainter extends CustomPainter {
  MyCustomPainter(
      {this.rectList = const [],
      required this.dx,
      required this.dy,
      required this.scaleX,
      required this.scaleY,
      required this.imgSize,
      required this.rotationAngle});

  List<RectInfoModel> rectList;

  late TransformVertexModel transformVertex;

  final double dx;
  final double dy;
  final double rotationAngle;

  final double scaleX;
  final double scaleY;
  final Size imgSize;
  final double dz = 1;

  // 定义缩放变量
  // final double scaleX = 1;
  // final double scaleY = 1;
  final double scaleZ = 1;

  @override
  void paint(Canvas canvas, Size size) {
    rectList.clear();
    // TODO: implement paint
    // print("size：${size}");
    Paint _paint = Paint();
    CanvasUtils.drawGrid(canvas, _paint, size);
    CanvasUtils.drawCoor(canvas, _paint, size);
    // canvas.translate(imgSize.width / 2, imgSize.height / 2);
    // 平移矩阵：最后一列的 [dx,dy,dz,1]
    //         [
    //           1,   0,   0,   0,
    //           0,   1,   0,   0,
    //           0,   0,   1,   0,
    //           dx,  dy,  dz,  1   // 注意这里的50
    //         ]
    //

    // 缩放矩阵
    //         [
    //           sx,   0,   0,   0,
    //           0,   sy,   0,   0,
    //           0,   0,   sz,   0,
    //           0,   0,   0,   1
    //         ]

    // 旋转矩阵
    //围绕z轴
    //   顺时针
    //         [
    //           cos(angle),   sin(angle),    0,   0,
    //           -sin(angle),   cos(angle),   0,   0,
    //           0,                    0,     1,   0,
    //           0,                    0,     0,   1
    //         ]
    //   逆时针
    //         [
    //           cos(angle),   -sin(angle),   0,   0,
    //           sin(angle),   cos(angle),    0,   0,
    //           0,                    0,     1,   0,
    //           0,                     0,     0,   1
    //         ]
    // 围绕X轴
    //   顺时针
    //        [
    //          1,           0,          0,         0,
    //          0,  cos(angle),   sin(angle),       0,
    //          0, -sin(angle),   cos(angle),       0,
    //          0,           0,            0,       1
    //        ]
    //
    //   逆时针
    //        [
    //          1,           0,          0,         0,
    //          0,  cos(angle),   -sin(angle),      0,
    //          0,  sin(angle),   cos(angle),       0,
    //          0,           0,            0,       1
    //        ]

    // 围绕Y轴
    //   顺时针
    //     [
    //       1,           0,          0,         0,
    //       0,  cos(angle),   sin(angle),       0,
    //       0, -sin(angle),   cos(angle),       0,
    //       0,           0,            0,       1
    //     ]
    //
    //   逆时针
    //     [
    //       1,           0,          0,         0,
    //       0,  cos(angle),   -sin(angle),      0,
    //       0,  sin(angle),   cos(angle),       0,
    //       0,           0,            0,       1
    //     ]

    // 计算倾斜的矩阵  skewXMatrix
    //     [
    //       1,             tan(skXAngle),  0,   0,
    //       tan(skYAngle),             1,              0,   0,
    //       0,             0,              1,   0,
    //       0, 0,  0,   1
    //     ]

    // List<List<double>> matrix4List = [
    //   [scaleX * math.cos(rotationAngle), math.sin(rotationAngle), 0, 0],
    //   [-math.sin(rotationAngle), scaleY * math.cos(rotationAngle), 0, 0],
    //   [0, 0, scaleZ, 0],
    //   [dx, dy, dz, 1],
    // ];

    // 创建一个 Matrix4 实例
    // final matrix4 =
    //     Matrix4.fromList(matrix4List.expand((element) => element).toList());

    // 设置矩阵的元素
    // matrix4.setEntry(1, 1, math.cos(rotationAngle));
    // matrix4.setEntry(1, 2, -math.sin(rotationAngle));
    // matrix4.setEntry(2, 1, math.sin(rotationAngle));
    // matrix4.setEntry(2, 2, math.cos(rotationAngle));
// matrix4.translate(x)
    // Matrix4 translationMatrix = Matrix4.translationValues(dx, dy, 0);
    // Matrix4 translationMatrix = Matrix4.translationValues(dx, dy, 0);

    // var originalStrokeWidth = 1;
    // canvas.translate(dx, dy);
    canvas.save();
    // 把矩形的中心点找出来
    Rect boxRect = Rect.fromLTRB(0, 0, imgSize.width, imgSize.height);
    // 把矩形的中心点找出来
    final rectCenter = boxRect.center;
    //  skew添加倾斜 / Matrix4.identity();  Matrix4.skew(0.0, 0.0); //
    Matrix4 matrix4 = Matrix4.identity();
    // ..translate(dx, dy)
    // ..rotateZ(rotationAngle);
    // ..scale(scaleX, scaleY);

    matrix4.translate(dx, dy);
    matrix4.translate(imgSize.width * scaleX / 2, imgSize.height * scaleY / 2);
    matrix4.rotateZ(rotationAngle);
    // 缩放之前先旋转，不然有问题

    matrix4.translate(
        -imgSize.width * scaleX / 2, -imgSize.height * scaleY / 2);

    // 旋转之前先倾斜，不然有问题
    //  x轴的倾斜
    // matrix4.setEntry(0, 1, 0.0);
    // y轴的倾斜
    // matrix4.setEntry(1, 0, 0.0);
    matrix4.scale(scaleX, scaleY);

    // canvas.translate(rectCenter.dx, rectCenter.dy);
    canvas.transform(matrix4.storage);
    // canvas.translate(-rectCenter.dx, -rectCenter.dy);

    final renderCenterRect = Rect.fromCenter(
        center: rectCenter, width: boxRect.width, height: boxRect.height);

    // rectList.add(
    //     RectInfoModel(rect: renderCenterRect, type: CanvasEventType.image));
    canvas.drawRect(
      boxRect,
      _paint..color = Colors.red,
    );

    canvas.restore();
    // 把矩形的中心点计算出来因为上面旋转的时候，先平移到矩形中心点 再旋转的
    Offset _center = Offset(dx + boxRect.width / 2, dy + boxRect.height / 2);

    // computedRotatePoint(canvas, _paint, boxRect);

    canvas.save();
    // canvas.translate(_center.dx + 100, _center.dy);
    // 计算旋转后的矩形坐标
    // 应用矩阵变换到矩形的每个角点
    vector.Vector4 topLef = vector.Vector4(
        -imgSize.width / 2, -imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;
    vector.Vector4 topRight = vector.Vector4(
        imgSize.width / 2, -imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;

    vector.Vector4 bottomRight = vector.Vector4(
        imgSize.width / 2, imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;
    vector.Vector4 bottomLeft = vector.Vector4(
        -imgSize.width / 2, imgSize.height / 2, 0, 0); // 使用Vector3表示一个点;

    vector.Vector4 topLeftPosition = matrix4.transformed(topLef);
    vector.Vector4 topRightPosition = matrix4.transformed(topRight);
    vector.Vector4 bottomRightPosition = matrix4.transformed(bottomRight);
    vector.Vector4 bottomLeftPosition = matrix4.transformed(bottomLeft);

    transformVertex = TransformVertexModel(
      topLeft: Offset(topLeftPosition.x, topLeftPosition.y),
      topRight: Offset(topRightPosition.x, topRightPosition.y),
      bottomRight: Offset(bottomRightPosition.x, bottomRightPosition.y),
      bottomLeft: Offset(bottomLeftPosition.x, bottomLeftPosition.y),
    );

    Path rotatePath = Path()
      ..moveTo(
          transformVertex.topLeft.dx, transformVertex.topLeft.dy); // 移动到第一个顶点
    rotatePath
      ..lineTo(transformVertex.topRight.dx, transformVertex.topRight.dy)
      ..lineTo(transformVertex.bottomRight.dx, transformVertex.bottomRight.dy)
      ..lineTo(transformVertex.bottomLeft.dx, transformVertex.bottomLeft.dy);
    rotatePath.close(); // 封闭路径

// 将路径的起点移动到指定位置 使用path.shift的方式修正偏移量，这里的起始点是原点距离矩形的正常距离，shift方法修正了偏移量,所以上面判断的时候，屏幕触摸的dx跟dy都不需要减去偏移量也不需要处理矩形中心点位移的情况
//     rotatePath = rotatePath.shift(_center + Offset(100, 0));
    rotatePath = rotatePath.shift(_center);
    // 绘制矩形
    _paint
      ..color = Colors.greenAccent
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    canvas.drawPath(rotatePath, _paint);
    rectList.add(RectInfoModel(
        rect: Rect.zero, path: rotatePath, type: CanvasEventType.image));
    canvas.restore();

    //绘制操作按钮
    drawActionBtn(canvas, _paint, _center);
  }

  // 绘制矩形操作按钮
  drawActionBtn(Canvas canvas, Paint paint, Offset center) {
    // canvas.save();
    // // canvas.translate(dx, dy);
    // // canvas.translate(boxRect.width / 2, boxRect.height / 2);
    // // 添加一个旋转的tap
    // Rect tapRect =
    //     Rect.fromLTRB(imgSize.width + dx, dy - 30, imgSize.width + dx + 30, dy);
    // canvas.drawRect(
    //     tapRect,
    //     paint
    //       ..color = Colors.pink
    //       ..style = PaintingStyle.fill);
    // rectList.add(RectInfoModel(rect: tapRect, type: CanvasEventType.rotate));
    //
    // canvas.restore();

    // 记住 要restore后重新平移原点再画，不然就是从之前的点开始，会不准
    // 传入原矩形原始屏幕的顶点坐标
    /// 添加一个缩放的tap 使用旋转后的顶点+ 平移矩形中心旋转的偏移量
    double scaleRectLeft =
        transformVertex.bottomRight.dx + dx + imgSize.width / 2;
    double scaleRectTop =
        transformVertex.bottomRight.dy + dy + imgSize.height / 2;

    drawVertexRect(
        canvas: canvas,
        rotationAngle: rotationAngle,
        vertexType: RotateVertexType.bottomRight,
        paint: paint..color = Colors.blue,
        eventType: CanvasEventType.scale,
        rectList: rectList,
        originVertex: Offset(scaleRectLeft, scaleRectTop));

    double rotateRectLeft =
        transformVertex.topRight.dx + dx + imgSize.width / 2;
    double rotateRectTop =
        transformVertex.topRight.dy + dy + imgSize.height / 2;

    drawVertexRect(
        canvas: canvas,
        paint: paint..color = Colors.deepOrangeAccent,
        rotationAngle: rotationAngle,
        eventType: CanvasEventType.rotate,
        vertexType: RotateVertexType.topRight,
        rectList: rectList,
        originVertex: Offset(rotateRectLeft, rotateRectTop));

    // double lockRectLeft = transformVertex.topLeft.dx + dx + imgSize.width / 2;
    // double lockRectTop = transformVertex.topLeft.dy + dy + imgSize.height / 2;
    //
    // drawVertexRect(
    //     canvas: canvas,
    //     paint: paint,
    //     rotationAngle: rotationAngle,
    //     eventType: CanvasEventType.rotate,
    //     paintColor: Colors.black,
    //     vertexType: RotateVertexType.topLeft,
    //     rectList: rectList,
    //     originVertex: Offset(lockRectLeft, lockRectTop));
    //
    // double deleteRectLeft =
    //     transformVertex.bottomLeft.dx + dx + imgSize.width / 2;
    // double deleteRectTop =
    //     transformVertex.bottomLeft.dy + dy + imgSize.height / 2;
    //
    // drawVertexRect(
    //     canvas: canvas,
    //     paint: paint,
    //     rotationAngle: rotationAngle,
    //     eventType: CanvasEventType.rotate,
    //     paintColor: Colors.orangeAccent,
    //     vertexType: RotateVertexType.bottomLeft,
    //     rectList: rectList,
    //     originVertex: Offset(deleteRectLeft, deleteRectTop));
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}

void drawVertexRect({
  scaleIconSize = const Size(30, 30),
  required Canvas canvas,
  required Paint paint,
  required double rotationAngle,
  CanvasEventType eventType = CanvasEventType.image,
  RotateVertexType vertexType = RotateVertexType.bottomRight,
  required List<RectInfoModel> rectList,
  // 对齐的顶点实际屏幕坐标
  required Offset originVertex,
}) {
  canvas.save();

  // 每次都以平移后的点为原点绘制
  // canvas.translate(dx, dy);

  /// 添加一个缩放的tap 使用旋转后的顶点+ 平移矩形中心旋转的偏移量
  double _scaleRectLeft = originVertex.dx;
  double _scaleRectTop = originVertex.dy;
  Rect scaleTapRect = Rect.fromLTRB(
      _scaleRectLeft, _scaleRectTop, _scaleRectLeft + 30, _scaleRectTop + 30);

  // 绘制矩形路径
  Size scaleIconSize = Size(30, 30);
  List<Offset> _scaleOffsetList =
      getRotatePoint(scaleIconSize, Offset.zero, rotationAngle);
  double _vertextX;
  double _vertextY;
  if (vertexType == RotateVertexType.bottomRight) {
    // 传入原始矩形是右下顶点，对齐左上顶点
    _vertextX = _scaleOffsetList[0].dx;
    _vertextY = _scaleOffsetList[0].dy;
  } else if (vertexType == RotateVertexType.topRight) {
    // 传入原始矩形是右上顶点，对齐左上顶点
    _vertextX = _scaleOffsetList[3].dx;
    _vertextY = _scaleOffsetList[3].dy;
  } else if (vertexType == RotateVertexType.topLeft) {
    _vertextX = _scaleOffsetList[2].dx;
    _vertextY = _scaleOffsetList[2].dy;
  } else {
    _vertextX = _scaleOffsetList[1].dx;
    _vertextY = _scaleOffsetList[1].dy;
  }
  // 计算原始矩形右下顶点跟操作按钮矩形的左上顶点, 两个顶点的偏移量，然后减去这个偏移量
  double _scaleIconOffsetX =
      originVertex.dx - (scaleTapRect.center.dx + _vertextX);
  double _scaleIconOffsetY =
      originVertex.dy - (scaleTapRect.center.dy + _vertextY);

  Path _scaleIconPath = Path()
    ..moveTo(_scaleOffsetList[0].dx, _scaleOffsetList[0].dy); // 移动到第一个顶点
  for (int i = 1; i < _scaleOffsetList.length; i++) {
    _scaleIconPath.lineTo(
        _scaleOffsetList[i].dx, _scaleOffsetList[i].dy); // 添加线段
  }
  _scaleIconPath.close(); // 封闭路径
  // 把偏移量加回去, 这样就可以对其顶点了
  _scaleIconPath = _scaleIconPath.shift(
      scaleTapRect.center + Offset(_scaleIconOffsetX, _scaleIconOffsetY));
  // 绘制矩形
  paint
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;

  // canvas.translate(50, 200);
  canvas.drawPath(_scaleIconPath, paint);

  rectList.add(
      RectInfoModel(rect: Rect.zero, path: _scaleIconPath, type: eventType));

  canvas.restore();
}

List<Offset> getRotatePoint(Size imgSize, Offset center, double rotationAngle) {
  // double rotationAngle = math.pi / 3; // 旋转角度，单位为弧度

  // 计算矩形的中心点坐标
  // Offset center = Offset(0.0, 0.0); // 假设矩形中心点在原点

  // 计算每个顶点相对于中心点的坐标
  double halfWidth = imgSize.width / 2;
  double halfHeight = imgSize.height / 2;
  List<Offset> vertices = [
    Offset(-halfWidth, -halfHeight), // 左上角顶点
    Offset(halfWidth, -halfHeight), // 右上角顶点
    Offset(halfWidth, halfHeight), // 右下角顶点
    Offset(-halfWidth, halfHeight), // 左下角顶点
  ];

  // 应用旋转矩阵来计算旋转后的坐标
  List<Offset> rotatedVertices = [];
  for (var vertex in vertices) {
    double rotatedX = vertex.dx * math.cos(rotationAngle) -
        vertex.dy * math.sin(rotationAngle);
    double rotatedY = vertex.dx * math.sin(rotationAngle) +
        vertex.dy * math.cos(rotationAngle);
    rotatedVertices.add(Offset(rotatedX, rotatedY));
  }

  // 输出结果
  // print("旋转后的顶点坐标:");
  // for (var i = 0; i < vertices.length; i++) {
  // print("顶点${i + 1}: (${rotatedVertices[i].dx}, ${rotatedVertices[i].dy})");
  // }
  return rotatedVertices;
}

//
// List<Offset> getRotateVertices(
//   List<Offset> rectVertices,
//   Offset rectCenter,
//   double rotationAngle,
// ) {
//   final rotationMatrix = Matrix4.rotationZ(rotationAngle); // 构造旋转矩阵
// // 计算矩形旋转后的四个顶点的偏移量
//
//   //
//   // final rotatedRectVertices = rectVertices.map((vertex) {
//   //   final offset = vertex - rectCenter; // 计算相对于中心点的偏移量
//   //   final rotatedX = offset.dx * cosAngle - offset.dy * sinAngle; // 应用旋转矩阵
//   //   final rotatedY = offset.dx * sinAngle + offset.dy * cosAngle;
//   //   return Offset(rotatedX + rectCenter.dx, rotatedY + rectCenter.dy); // 计算旋转后的顶点位置
//   // }).toList();
// }

/// 通过计算旋转的坐标渲染旋转后的矩形
computedRotatePoint(Canvas canvas, Paint paint, Rect boxRect, Size imgSize,
    double rotationAngle) {
  canvas.save();
  Offset _center = Offset(boxRect.width / 2, boxRect.height / 2);

  //使用平移的方式修正偏移量，这里的起始点事原点，0，0
  // canvas.translate(_center.dx, _center.dy);

  // print("中心点：$_center");
  List<Offset> _rotateOffsetList =
      getRotatePoint(imgSize, _center, rotationAngle);

  //方案：获取旋转后的四个顶点，然后用path画出来，这时候有两个方案可以处理
  // 第一个方案：画布平移到矩形的中心点，因为drawPath 是以原点即是左上角为原点，所以在
  // 判断点击事件的时候，需要把触摸点的偏移量重置为原点，就是 localPosition - Offset(dx+imgSize/2,dy+imgSize/2),把之前的偏移量去掉，就是原点了,因为之前旋转的时候，位移到了矩形的原点位置，这里得加回去
  //
  // 第二个方案：更改path的起始点，path.shift方法，把path的起点位移到矩形的中心点，  这样的话，path就是没有偏移量计算的，因为在更改起点的时候，把dx跟dy加进去了，
  // 所以在判断点击事件的时候，需要把触摸点的偏移量重置为原点，就是 localPosition + Offset(dx,dy),把之前的偏移量加上，就是当前点击的位置了，因为之前判断矩形点击的时候，都是把 localPosition - Offset(dx,dy) 来判断的，这样矩形的原点以及判断的原点都是0，0开始的,
  // 或者直接用globalPosition    直接判断，不用之前减去偏移量的值，因为之前减去偏移量的值是为了判断计算矩形点击域减去的
  // 绘制矩形路径
  Path path = Path()
    ..moveTo(_rotateOffsetList[0].dx, _rotateOffsetList[0].dy); // 移动到第一个顶点
  for (int i = 1; i < _rotateOffsetList.length; i++) {
    path.lineTo(_rotateOffsetList[i].dx, _rotateOffsetList[i].dy); // 添加线段
  }
  path.close(); // 封闭路径
// 将路径的起点移动到指定位置 使用path.shift的方式修正偏移量，这里的起始点是原点距离矩形的正常距离，shift方法修正了偏移量,所以上面判断的时候，屏幕触摸的dx跟dy都不需要减去偏移量也不需要处理矩形中心点位移的情况
  path = path.shift(_center);
  // 绘制矩形
  paint
    ..color = Colors.blue
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2.0;
  canvas.drawPath(path, paint);
  // 这里的rect 以左上角 也就是（0，0） 为原点的，平移那些操作的原点是以offSet(dx,dy) 来做的，所以这里需要修正一下矩形的原点
  // Rect pathRect = path.getBounds();
  // canvas.drawRect(pathRect, _paint..color = Colors.blue);
  // Rect _correctRect = Rect.fromLTRB(pathRect.left - dx, pathRect.top - dy,
  //     pathRect.right - dx, pathRect.bottom - dy);
  // print("变换后的矩形：${path.getBounds()}");
  // rectList.add(RectInfoModel(
  //     rect: Rect.zero, path: path, type: CanvasEventType.image));

  canvas.restore();
}

enum RotateVertexType { topLeft, topRight, bottomRight, bottomLeft }
